package com.cn.wanxi.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;

public class FileUpload {

    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";


    public static String upload(HttpServletRequest req) {

        // 配置上传参数,给前端传递到后台的文件分配一个空间，用于临时存储文件（缓存）
        DiskFileItemFactory factory = new DiskFileItemFactory();
//        解析将前端传递过来的数据进行解析
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 中文处理
        upload.setHeaderEncoding("UTF-8");
        // 这个路径相对当前应用的目录,得到当前项目编译的路径
        String uploadPath = req.getServletContext().getRealPath("./");
        // 如果目录不存在则创建,创建文件保存的路径
        createFile(uploadPath);
        try {
            // 解析请求的内容提取文件数据
            List<FileItem> formItems = upload.parseRequest(req);
            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理普通表单中的字段，只需要判断是否是文件即可
                    if (!item.isFormField()) {
//                        取得文件名称
                        String fileName = new File(item.getName()).getName();
//                        对文件名称进行重新命名
//                        System.currentTimeMillis()拿到系统时间的毫秒数
//                        1658392724864--aa.jpg
                        fileName = System.currentTimeMillis() + "--" + fileName;
//                        将文件保存到服务器的地址
                        String filePath = uploadPath + "/" + UPLOAD_DIRECTORY + "/" + fileName;
                        File storeFile = new File(filePath);
                        // 保存文件到硬盘
                        item.write(storeFile);
//                        需要将out里面的文件拷贝到web里面去
                        String webPath = getWebPath(uploadPath);
//                        createFile(webPath);
//                        File webPathFile = new File(webPath + "/" + UPLOAD_DIRECTORY + "/" + fileName);
//                        item.write(webPathFile);有可能item只能得到一次，
                        copy(filePath, webPath, fileName);
                        return "/" + UPLOAD_DIRECTORY + "/" + fileName;
                    }
                }
            }
        } catch (Exception ex) {

        }
        return "";
    }

    /**
     * 创建文件夹，首先判断当前文件夹是否存在
     * 每次创建的文件夹都是UPLOAD_DIRECTORY
     *
     * @param path
     */
    private static void createFile(String path) {
        File uploadDir = new File(path, UPLOAD_DIRECTORY);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
    }

    /**
     * 截取字符串，拼接到web下面的路径
     *
     * @param path
     * @return
     */
    private static String getWebPath(String path) {
//        E:\wanxi\step-4\canyin04-0613\out\artifacts\canyin04_0613_war_exploded
        return path.split("out")[0] + "/web/";

    }

    /**
     * 将一个文件读取到另一个文件
     *
     * @param oldPath
     * @param newPath
     */
    private static void copy(String oldPath, String newPath, String fileName) {
        createFile(newPath);
        try {
            InputStream inputStream = new FileInputStream(oldPath);
            int read = 0;
            OutputStream outputStream = new FileOutputStream(newPath + "/" + UPLOAD_DIRECTORY + "/" + fileName);
            while ((read = inputStream.read()) != -1) {
                outputStream.write(read);
            }
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}